/**
 * Created by PanJiaChen on 16/11/18.
 */

/**
 * Parse the time to string
 * @param {(Object|string|number)} time
 * @param {string} cFormat
 * @returns {string | null}
 */
export function parseTime(time, cFormat) {
  if (arguments.length === 0 || !time) {
    return null
  }
  const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}'
  let date
  if (typeof time === 'object') {
    date = time
  } else {
    if (typeof time === 'string') {
      if (/^[0-9]+$/.test(time)) {
        // support "1548221490638"
        time = parseInt(time)
      } else {
        // support safari
        // https://stackoverflow.com/questions/4310953/invalid-date-in-safari
        time = time.replace(new RegExp(/-/gm), '/')
      }
    }

    if (typeof time === 'number' && time.toString().length === 10) {
      time = time * 1000
    }
    date = new Date(time)
  }
  const formatObj = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
    a: date.getDay()
  }
  const time_str = format.replace(/{([ymdhisa])+}/g, (result, key) => {
    const value = formatObj[key]
    // Note: getDay() returns 0 on Sunday
    if (key === 'a') {
      return ['日', '一', '二', '三', '四', '五', '六'][value]
    }
    return value.toString().padStart(2, '0')
  })
  return time_str
}

/**
 * @param {number} time
 * @param {string} option
 * @returns {string}
 */
export function formatTime(time, option) {
  if (('' + time).length === 10) {
    time = parseInt(time) * 1000
  } else {
    time = +time
  }
  const d = new Date(time)
  const now = Date.now()

  const diff = (now - d) / 1000

  if (diff < 30) {
    return '刚刚'
  } else if (diff < 3600) {
    // less 1 hour
    return Math.ceil(diff / 60) + '分钟前'
  } else if (diff < 3600 * 24) {
    return Math.ceil(diff / 3600) + '小时前'
  } else if (diff < 3600 * 24 * 2) {
    return '1天前'
  }
  if (option) {
    return parseTime(time, option)
  } else {
    return (
      d.getMonth() +
      1 +
      '月' +
      d.getDate() +
      '日' +
      d.getHours() +
      '时' +
      d.getMinutes() +
      '分'
    )
  }
}

/**
 * @param {string} url
 * @returns {Object}
 */
export function param2Obj(url) {
  const search = decodeURIComponent(url.split('?')[1]).replace(/\+/g, ' ')
  if (!search) {
    return {}
  }
  const obj = {}
  const searchArr = search.split('&')
  searchArr.forEach((v) => {
    const index = v.indexOf('=')
    if (index !== -1) {
      const name = v.substring(0, index)
      const val = v.substring(index + 1, v.length)
      obj[name] = val
    }
  })
  return obj
}

// AES加密引入crypto
import CryptoJS from 'crypto-js'
CryptoJS.enc.u8array = {
  /**
   * Converts a word array to a Uint8Array.
   *
   * @param {WordArray} wordArray The word array.
   *
   * @return {Uint8Array} The Uint8Array.
   *
   * @static
   *
   * @example
   *
   *     var u8arr = CryptoJS.enc.u8array.stringify(wordArray);
   */
  stringify: function (wordArray) {
      // Shortcuts
      var words = wordArray.words;
      var sigBytes = wordArray.sigBytes;

      // Convert
      var u8 = new Uint8Array(sigBytes);
      for (var i = 0; i < sigBytes; i++) {
          var byte = (words[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff;
          u8[i]=byte;
      }

      return u8;
  },

  /**
   * Converts a Uint8Array to a word array.
   *
   * @param {string} u8Str The Uint8Array.
   *
   * @return {WordArray} The word array.
   *
   * @static
   *
   * @example
   *
   *     var wordArray = CryptoJS.enc.u8array.parse(u8arr);
   */
  parse: function (u8arr) {
      // Shortcut
      var len = u8arr.length;

      // Convert
      var words = [];
      for (var i = 0; i < len; i++) {
          words[i >>> 2] |= (u8arr[i] & 0xff) << (24 - (i % 4) * 8);
      }

      return CryptoJS.lib.WordArray.create(words, len);
  }
};
/**
 * 加密函数
 * @param {string} value
 */
export function toEncrypt(value) {
  const key = CryptoJS.enc.Utf8.parse(
    //将秘钥转换成Utf8字节数组
    CryptoJS.MD5('_hS2@17_')
      .toString()
      .toUpperCase()
  )
  const password = CryptoJS.enc.Utf8.parse(value)
  const encrypted = CryptoJS.AES.encrypt(password, key, {
    mode: CryptoJS.mode.ECB,
    padding: CryptoJS.pad.Pkcs7
  })
  return encrypted.toString()
}

export function toEncryptFile(value) {
  const key = CryptoJS.enc.Utf8.parse(
    //将秘钥转换成Utf8字节数组
    CryptoJS.MD5('_hS2@17_')
      .toString()
      .toUpperCase()
  )
  const contentWA = CryptoJS.enc.u8array.parse(value)
  var encrypted = CryptoJS.AES.encrypt(contentWA, key, {
    mode: CryptoJS.mode.ECB,
    padding: CryptoJS.pad.Pkcs7
  })
  var bv = CryptoJS.enc.u8array.stringify(encrypted.ciphertext)
  return bv
}

// 时间格式化2
export function dataFormat2(data) {
  const year = data.getFullYear()
  const month = data.getMonth() + 1
  // const day = data.getDate()
  const newTime = year + '年' + month + '月'
  // const newTime = year + '-' + (month < 10 ? '0' + month : month) + '-' + (day < 10 ? '0' + day : day)
  return newTime
}
// 时间格式化3
export function dataFormat3(data) {
  const year = data.getFullYear()
  const month = data.getMonth() + 1
  const day = data.getDate()
  // const newTime = year + '年' + month + '月'
  const newTime =
    year +
    '-' +
    (month < 10 ? '0' + month : month) +
    '-' +
    (day < 10 ? '0' + day : day)
  return newTime
}

// 时间格式化
export function dataFormat(data) {
  const year = data.getFullYear()
  const month = data.getMonth() + 1
  // const day = data.getDate()
  // const newTime = year + '年' + month + '月'
  const newTime = year + '-' + (month < 10 ? '0' + month : month)
  return newTime
}

export function formatAmount(strData, n) {
  var CurrencyAndAmountRegExp = /^(\d{1,18})|(\d{1,18}\.)|(\d{1,17}\.\d{0,1})|(\d{1,16}\.\d{0,2})|(\.\d{1,2})$/
  var _result = CurrencyAndAmountRegExp.test(strData)
  if (_result === false) {
    return ''
  }
  // 一般来说最多就6位吧，当然如果有特殊需求可自行更改(｀・∀・´)
  n = n > 0 && n <= 6 ? n : 2
  var formatData =
    parseFloat((strData + '').replace(/[^\d-]/g, '')).toFixed(n) + ''
  var l = formatData
    .split('.')[0]
    .split('')
    .reverse()
  var r = formatData.split('.')[1]
  var t = ''
  for (let i = 0; i < l.length; i++) {
    t += l[i] + ((i + 1) % 3 === 0 && i + 1 !== l.length ? ',' : '')
  }
  return (
    t
      .split('')
      .reverse()
      .join('') +
    '.' +
    r
  )
}

export function formatCurrency(num) {
  num = num.toString().replace(/\$|/g, '')
  if (isNaN(num)) num = '0'
  var sign = num == (num = Math.abs(num))
  num = Math.floor(num * 100 + 0.50000000001)
  var cents = num % 100
  num = Math.floor(num / 100).toString()
  if (cents < 10) cents = '0' + cents
  for (var i = 0; i < Math.floor((num.length - (1 + i)) / 3); i++)
    num =
      num.substring(0, num.length - (4 * i + 3)) +
      ',' +
      num.substring(num.length - (4 * i + 3))
  return (sign ? '' : '-') + num + '.' + cents
}

/**
 * 深拷贝数据
 * @param {Object} val
 */
export function deepCopy(val) {
  return JSON.parse(JSON.stringify(val))
}
